#!/usr/bin/python3
# -*- coding:UTF-8 -*-

import AutoExecUtils
import os
import traceback
import argparse
import json
from bson.json_util import dumps, loads


def usage():
    pname = os.path.basename(__file__)
    print(pname + " --outputfile <path> ")
    exit(1)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--starttime", default="", help="Data minimum renew time")
    parser.add_argument(
        "--batchtag", default="", help="Json document tag for this batch"
    )
    parser.add_argument(
        "--collectionObjs", default="{}", help="Collections map to trigger cmdb import"
    )

    args = parser.parse_args()
    startTime = args.starttime
    batchTag = args.batchtag
    collectionsMap = json.loads(args.collectionObjs)
    collectionObjs = []
    for key in collectionsMap :
        keys = key.split('/')
        collectionObjs.append({"category": "{}".format(keys[0]), "type": keys[1]})

    if startTime is None or startTime == "":
        startTime = 0

    try:
        AutoExecUtils.callNativeApi(
            "/neatlogic/api/rest/cmdb/sync/cicollection/launch",
            {
                "startTime": int(1000 * float(startTime)),
                "batchTag": batchTag,
                "collectionObjList": collectionObjs
            },
        )
    except Exception as err:
        print("ERROR: Trigger cmdb import failed, {}".format(err))
        exit(-1)
